using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Collections;

namespace ThaiLanguageTools
{
    public class QueryList 
    {
        Dictionary<String, QueryInfo> _uniqueSet = new Dictionary<String, QueryInfo>();

        public void TryAddQuery(QueryInfo query)
        {
            Debug.Assert(query != null);

            QueryInfo exQuery;
            if (_uniqueSet.TryGetValue(query.Text, out exQuery))
            {
                // Update with one of higher probability
                if (query.Probability > exQuery.Probability) { _uniqueSet[query.Text] = query; }
            }
            else
            {
                // Add if it doesn't exist
                _uniqueSet.Add(query.Text, query);
            }
        }

        public List<QueryInfo> GetQueryListCopy(bool sort)
        {
            List<QueryInfo> ql = new List<QueryInfo>(_uniqueSet.Values);
            if (sort) { ql.Sort(ProbabilityComparison); }
            return ql;
        }

        int ProbabilityComparison(QueryInfo x, QueryInfo y)
        {
            // Compare by inverted probability, then alphabetic
            int cp = -1 * _uniqueSet[x.Text].Probability.CompareTo(_uniqueSet[y.Text].Probability);
            if (cp == 0) { cp = x.Text.CompareTo(y.Text); }
            return cp;
        }

        public decimal GetProbability(String query)
        {
            return _uniqueSet[query].Probability;
        }

        public bool Contains(String query)
        {
            return _uniqueSet.ContainsKey(query);
        }

        public int Count { get { return _uniqueSet.Count; } }
    }
}
